import cv2
import numpy as np

if __name__ == '__main__':
    # 1. 图片输入
    image_np = cv2.imread('America.jpg')

    # 2. 灰度化
    image_np_gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)

    # 3. 二值化
    _, image_np_thresh = cv2.threshold(
        image_np_gray,
        60,
        255,
        cv2.THRESH_BINARY
    )

    # 4. 查找轮廓
    contours, hierarchy = cv2.findContours(
        image_np_thresh,
        cv2.RETR_EXTERNAL,
        cv2.CHAIN_APPROX_SIMPLE
    )

    # 5. 绘制轮廓
    cv2.drawContours(
        image_np,
        contours,
        contourIdx=-1,
        color=(0, 0, 255),
        thickness=2
    )

    # 6. 外界轮廓
    contour_image = image_np.copy()
    # 遍历轮廓
    for cnt in contours:
        # 计算最小外接圆
        # 返回值：圆心和半径
        (x, y), radius = cv2.minEnclosingCircle(cnt)
        # 转整形
        x, y, radius = int(x), int(y), int(radius)
        print(f"圆心({x},{y}), 半径{radius}")
        # 画圆
        cv2.circle(
            contour_image,  # 在哪里画
            (x, y),  # 圆心
            radius,  # 半径
            (255, 0, 0),  # 颜色
            2,  # 粗度
            cv2.LINE_AA  # 抗锯齿
        )

    # 7. 图片输出
    cv2.imshow('image_np', image_np)
    cv2.imshow('contour_image', contour_image)
    cv2.imwrite('star.jpg', contour_image)
    cv2.waitKey(0)
